<script setup>
import {ref, reactive, watch, onMounted} from "vue";
import {addEmpApi, queryAllDeptApi, queryByIdApi, queryPageApi} from "@/api/emp";
import {Plus} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
// 初始化搜索表单
const searchEmp = reactive({
  name: '',
  gender: '',
  begin: '',
  end: '',
  date: []
})

//初始化员工列表
const empList = ref([])


// 深度侦听 searchEmp.date，用于更新 begin/end
watch(
    () => searchEmp.date,
    (newValue) => {
      if (Array.isArray(newValue) && newValue.length === 2) {
        [searchEmp.begin, searchEmp.end] = newValue;
      } else {
        searchEmp.begin = '';
        searchEmp.end = '';
      }
    },
    {deep: true}
);

// 初始化性别列表
const genderList = [
    {label: '男', value: '1'},
    {label: '女', value: '2'}
]

// 分页参数初始化 函数
const size = ref('default')
const disabled = ref(false)
const background = ref(true)
// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 执行分页搜索
const searchHandler = async () => {
  const res = await queryPageApi(currentPage.value, pageSize.value, searchEmp.name, searchEmp.gender, searchEmp.begin, searchEmp.end);
  empList.value = res.data.rows;
  total.value = res.data.total;
};


const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  searchHandler()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  searchHandler()
}

// 清空搜索表单
const clear = () => {
  //  清空搜索表单数据
  Object.keys(searchEmp).forEach(key => searchEmp[key] = '')
  searchHandler();
};

// 弹框控制
const dialogVisible = ref(false);

// 表单数据
const formData = reactive({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
});

const jobList = [
  {label: '班主任', value: '1'},
  {label: '讲师', value: '2'},
  {label: '学工主管', value: '3'},
  {label: '教研主管', value: '4'}
];

const deptList = ref([]);

const tips = ref('添加员工')
// 获取部门数据
const queryAllDept = async () => {
  let result = await queryAllDeptApi()
  deptList.value = result.data
}

// 展示弹框
const showDialog = () => {
  dialogVisible.value = true;
  resetForm()
};

const resetForm = () => {
  // 手动重置表单
  if(formData){
    Object.keys(formData).forEach(key=>formData[key]='')
    formData.exprList= []
  }
};

const handleClose = () => {
  dialogVisible.value = false
}

const addWorkExp = async () => {
  formData.exprList.push({
    date: [],
    company: '',
    job: '',
    begin: '',
    end: ''
  })
}

const delWorkExp = (index) => {
  formData.exprList.splice(index, 1)
}

// 图片上传
const handleAvatarSuccess = (response) => {
  formData.image=response.data
}

const beforeAvatarUpload = (rawFile) => {
  if ( !['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('上传图片格式必须是jpg或png格式的!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}

// 初始化校验表单数据
const ruleFormRef = ref(null);

// 表单校验规则
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
}

// 通过id查询员工数据
const queryById = async (id) => {
  let result = await queryByIdApi(id)
  Object.assign(formData, result.data);
  dialogVisible.value = true
  tips.value='修改员工'

  let exprList = formData.exprList
  if(exprList.length>0&&exprList){
    exprList.forEach(item=>{
      item.date=[item.begin,item.end]
    })
  }
}

// 深度监听工作经历时间范围
watch(
    () => formData.exprList,
    (newVal) => {
      newVal.forEach((item, index) => {
        if (item.date && item.date.length === 2) {
          [formData.exprList[index].begin, formData.exprList[index].end] = item.date;
        }
      });
    },
    {deep: true, immediate: true}
);

const save = async () => {
  // 校验表单
  if(!formData) return
  //
  await ruleFormRef.value.validate(async valid => {
    if(valid){
      let res=null
      if(formData.id){
        res = await updateEmpApi(formData)
      }else{
        res = await addEmpApi(formData)
      }
      if(res.code){
        ElMessage.success('操作成功')
        searchHandler()
        resetForm()
        dialogVisible.value = false
        tips.value='添加员工'
      }else{
        ElMessage.error('操作失败')
      }
    }else {
      ElMessage.warning('请填写正确的表单')
    }
  })

};


// 声明Token
let token = ref('')
//加载localStorage存储的员工登录信息
const loginUser =  localStorage.getItem('loginUser');
if(loginUser){
  token.value = JSON.parse(loginUser).token
}

onMounted(() => {
  queryAllDept()
  searchHandler()
});
</script>
<template>
  <h3>员工管理</h3>
  <!-- 搜索栏 -->
  <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="姓名" clearable style="width: 120px"/>
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="性别" clearable style="width: 120px">
        <el-option v-for="gender in genderList" :key="gender.value" :label="gender.label"
                   :value="gender.value"></el-option>
      </el-select>
    </el-form-item>
    <!--  时间范围选择  -->
    <el-form-item label="入职时间">
      <div class="block">
        <el-date-picker
            v-model="searchEmp.date"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchHandler">查询</el-button>
      <el-button type="default" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 新增员工按钮 -->
  <el-button type="primary" @click="showDialog">+ 新增员工</el-button>
  <!-- 批量删除按钮 -->
  <el-button type="danger" @click="deleteByIds">- 批量删除</el-button>

  <!-- 弹框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="tips"
      width="800px"
      :before-close="handleClose"
  >
    <!--  弹框内嵌表单  -->
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="formData"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
    >
      <el-row gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
                v-model="formData.name"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别">
              <el-option v-for="gender in genderList" :key="gender.value" :label="gender.label"
                         :value="gender.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-col :span="12">
          <el-form-item label="薪资" prop="salary">
            <el-input v-model="formData.salary"/>
          </el-form-item>
        </el-col>
        <el-form-item label="入职时间" prop="entryDate">
          <el-date-picker
              v-model="formData.entryDate"
              type="date"
              placeholder="请选择日期"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              :size="size"
          />
        </el-form-item>
      </el-row>
      <el-row gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门" prop="deptId">
            <el-select v-model="formData.deptId" placeholder="所属部门" clearable>
              <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-select v-model="formData.job" placeholder="职位" clearable>
              <el-option v-for="job in jobList" :key="job.value" :label="job.label" :value="job.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-form-item label="头像" property="image" width="100">
          <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :headers="{'token': token}"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" @click="addWorkExp" size="small">+添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(item,index) in formData.exprList" :key="index" :gutter="3" >
        <el-col :span="10">
          <el-form-item label="时间"  style="width: 280px">
            <el-date-picker
                v-model="item.date"
                type="daterange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :size="size"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司">
            <el-input v-model="item.company" size="small" style="width: 80px; padding-left: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位">
            <el-input v-model="item.job" size="small"/>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item >
            <el-button type="danger" @click="delWorkExp(index)" size="small">-删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>



      <el-form-item>
        <el-button type="primary" @click="save">
          提交
        </el-button>
        <el-button type="default" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 员工表格展示 -->
  <el-table :data="empList" style="width: 100%"
            border stripe
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55"/>

    <el-table-column property="id" label="ID" width="120"/>
    <el-table-column property="name" label="姓名" width="120"/>
    <el-table-column property="gender" label="性别" width="120">
      <template #default="scope">
        <span v-if="scope.row.gender==1">男</span>
        <span v-else>女</span>
      </template>
    </el-table-column>
    <el-table-column property="image" label="头像" width="120">
      <template #default="scope">
        <img :src="scope.row.image" alt="" style="width: 50px">
      </template>
    </el-table-column>
    <el-table-column property="deptName" label="所属部门" width="120"/>
    <el-table-column property="job" label="职位" width="120">
      <template #default="scope">
        <span v-if="scope.row.job==1">班主任</span>
        <span v-else-if="scope.row.job==2">讲师</span>
        <span v-else-if="scope.row.job==3">学工主管</span>
        <span v-else-if="scope.row.job==4">教研主管</span>
        <span v-else-if="scope.row.job==5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column property="entryDate" label="入职时间" width="120"/>
    <el-table-column prop="updateTime" label="最后修改时间"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" size="small" @click="queryById(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>
  <!-- 分页 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>
<style scoped>
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;


}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
</style>